import { DndCard } from '@/components/DndCard';
import { RightOutlined } from '@ant-design/icons';
import classNames from 'classnames';
import { isEmpty } from 'lodash-es';
import React, { useMemo } from 'react';
import OStyle from './index.less';
import type { YmCollaPanesProps } from './interface';

const YmCollaPanes: React.FC<YmCollaPanesProps> = (props) => {
  const {
    collPanesActiveKeys,
    onSetCollPanesActiveKeys,
    paneKey,
    children,
    collapsible = true,
    headerTitle,
    hiddenHeader = false,
    extra, //为了兼容item_content展开收起动画
    contentClass,
    dragAndDropParams,
  } = props;

  //打开关闭
  const onCollPane = (e: React.MouseEvent, index: number | string) => {
    e.stopPropagation();
    if (typeof onSetCollPanesActiveKeys !== 'function') return;
    const currIndex = collPanesActiveKeys.findIndex((val) => val === index);
    if (typeof currIndex === 'number' && currIndex > -1) {
      collPanesActiveKeys.splice(currIndex, 1);
    } else {
      collPanesActiveKeys.push(index);
    }
    onSetCollPanesActiveKeys([...(collPanesActiveKeys || [])]);
  };

  const headerRender = useMemo(() => {
    const headerDom = (
      <div className={OStyle.item_header}>
        <div
          className={OStyle.header_left}
          onClick={(e: React.MouseEvent) => {
            onCollPane(e, paneKey);
          }}
        >
          {collapsible && (
            <RightOutlined
              className={classNames(OStyle.left_collapse_icon, {
                [`${OStyle.icon_rotate}`]: collPanesActiveKeys?.includes(paneKey),
              })}
            />
          )}
          {typeof headerTitle === 'string' ? <span className={OStyle.left_text}>{headerTitle} </span> : headerTitle}
        </div>
        {/*右侧操作按钮按钮*/}
        <div className={OStyle.header_right}>{extra && extra}</div>
      </div>
    );
    if (!isEmpty(dragAndDropParams)) {
      const { index, dragAndDropKey, onCardMove } = dragAndDropParams;
      return (
        <DndCard
          key={paneKey}
          index={index}
          moveCard={(a: number, b: number) => {
            // onSetCollPanesActiveKeys?.([]);
            onCardMove(a, b);
          }}
          dragAndDropKey={dragAndDropKey}
        >
          {headerDom}
        </DndCard>
      );
    }

    return headerDom;
  }, [dragAndDropParams, paneKey, collPanesActiveKeys, headerTitle, extra]);

  return (
    <div className={OStyle.pane_item}>
      {!hiddenHeader ? headerRender : null}
      <div
        className={classNames(OStyle.item_content, contentClass, {
          [`${OStyle.content_hidden}`]: !collPanesActiveKeys?.includes(paneKey),
        })}
      >
        {children && children}
      </div>
    </div>
  );
};

export default YmCollaPanes;
